
/* global App, alertify */

(function() {
    
    var InstantMessagingModule = {
    
        account: null,
    
        init: function() {
            this.configureUI();
            this.configureSendInstant();
            this.configureGlobalSMS();
            this.loadAccountInfo();
            this.loadInstantHistory();
        },
        
        loadAccountInfo: function() {
            var self = this;
            var url = App.getBaseURL() + "sms/account_info";
            
            $.get(url, function(data) {
                if( data.status == 'success' ) {
                    self.account = data.account;
                }
            }, 'json');
        },
        
        accountInfoValid: function() {
            if( this.account == null ) {
                alertify.error("An SMS Messaging Account has not been setup for this organisation. Please contact support");
                return false;
            }
            
            if( !this.account.active ) {
                alertify.error("SMS Account Is Not Active. Please contact support");
                return false;
            }
            
            if( this.account.balance <= 0 ) {
                alertify.error("SMS Account is low on credit. Please top up to continue");
                return false;
            }
            
            if( this.account.balance < 50 && this.account.balance > 0 ) {
                alertify.warning("SMS Account Is low on credit. Account balance at " + this.account.balance + ".");
                return true;
            }
            
            if( !this.account.sender_id || this.account.sender_id.length > 11 ) {
                alertify.error("SMS Account Configuration Invalid. Sender ID not set or length is invalid");
                return false;
            }
            
            return true;
        },

        configureSendInstant: function() {
            var self = this;

            $('a[data-toggle="tab"]').on('shown.bs.tab', function( e ) {
                if ( $(e.target).attr('href') == "#instant-history" ) {
                    self.loadInstantHistory();
                }
            });

            $(document).on('click', '#send_instant_btn', function( e ) {
                e.preventDefault();

                var contacts = [],
                    message = $("#send_instant_form #send_instant_message").val();

                $(".pillbox li").each(function() {
                    contacts.push({
                        name: $(this).text(),
                        number: $(this).attr('data-number'),
                        member_id: $(this).attr('data-member-id')
                    });
                });

                if ( contacts.length == 0 ) {
                    return false;
                }

                if ( message.length == 0 ) {
                    alert('Please enter a message that you would like to send');
                    return;
                }

                confirm('You are about to send a direct SMS to the entered contacts. Do you want to continue?', function() {

                    function enableFields( enable ) {
                        if ( enable ) {
                            $("#send_instant_form input, #send_instant_form textarea").removeAttr('disabled');
                            $("#send_instant_form #send_instant_btn").addClass('btn-info').removeClass('btn-warning');
                        }
                        else {
                            $("#send_instant_form input, #send_instant_form textarea").attr('disabled', true);
                            $("#send_instant_form #send_instant_btn").addClass('btn-warning').removeClass('btn-info');
                        }
                    }

                    enableFields(false);

                    var url = $("#send_instant_form").attr('action');
                    var params = {
                        contacts: contacts,
                        message: message
                    };

                    $.ajax({
                        url: url,
                        data: params,
                        type: 'post',
                        dataType: 'json',
                        success: function( response ) {
                            alertify.success(response.message);

                            if ( response.status == 'success' ) {
                                $('#sms_account_balance').text(response.account_balance);
                                $("#send_instant_form textarea").val('');
                                $("#send_instant_form .pillbox li").remove();

                                self.loadInstantHistory();
                                
                                // if we are sending via the modal, then dismiss it afterwards
                                $("#sms_modal_dismiss").click();
                            }

                            else {
                                alertify.error(response.message);
                            }

                            enableFields(true);
                        },
                        error: function( xhr ) {
                            console.log(xhr.responseText);
                            enableFields(true);
                            alert("An error whiles trying to send this message. Please refresh and try again.");
                        }
                    });
                });
            });
        },

        configureGlobalSMS: function() {
            var self = this;

            $(document).on('click', ".send_sms_btn", function(e) {
                e.preventDefault();
                
                if( !self.accountInfoValid() ) {
                    return;
                }
                
                var numbers = [];
                var number = "" + $(this).attr('data-number'); // ensure we get the info as a string and not a number
                
                if( number ) {
                    numbers.push( number );
                }

                self.showSMSComposeDialog(numbers);
            });
            
            App.listen('sendSmsMessage', function(numbers) {
                if( !self.accountInfoValid() ) {
                    return;
                }
                
                self.showSMSComposeDialog(numbers);
            });
        },

        showSMSComposeDialog: function(numbers) {
            
            var self = this;
            var url = App.baseURL + "sms/instant_message_popup";

            var params = {
                numbers: numbers || []
            };

            $.post(url, params, function(html) {
                $("#ajaxModal").html(html);

                self.configureUI();

                $("#ajaxModal").modal();
                
                try {
                    var contacts = JSON.parse($("#preloaded_contacts").val());
                    if( contacts ) {
                        for(var i = 0; i < contacts.length; i++) {
                            self.addPill($(".pillbox input"), contacts[i]);
                        }
                    }
                } catch(e) {
                    console.log(e);
                }
            });

        },
        
        addPill: function( $input, $data ) {
            var $pills = $input.closest('.pillbox'), $repeat = false, $repeatPill;
            if ( $data.value == "" ) {
                return;
            }

            $("li", $pills).text(function( i, v ) {
                if ( v == $data.value ) {
                    $repeatPill = $(this);
                    $repeat = true;
                }
            });

            if ( $repeat ) {
                $repeatPill.fadeOut().fadeIn();
                return;
            }

            var $item = $('<li class="label bg-info" data-id="' + $data.id + '" data-member-id="' + $data.member_id + '" ' +
                    ' data-number="' + $data.number + '" title="' + $data.number + ' - Click to remove">' + $data.value + " (" + $data.type.substring(0, 1) + ")" + '</li> ');
            $item.insertBefore($input);
            $pills.trigger('change', $item);

            setTimeout(function() {
                $input.val('');
            }, 50);
        },

        configureUI: function() {
            var self = this;

            $(".pillbox input").autocomplete({
                source: $("#contacts-autocomplete-url").val(),
                minLength: 2,
                select: function( event, ui ) {
                    if ( ui.item ) {
                        self.addPill($(this), ui.item);
                        $(this).val('');
                    }
                },
                create: function() {
                    $(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
                        var that = this;

                        $.each(items, function( index, item ) {
                            var isPill = false;

                            $(".pillbox li").each(function() {
                                if( $(this).data('number') == item.number ) {
                                    isPill = true;
                                    return false;
                                }
                            });

                            if( !isPill ) {
                                that._renderItemData(ul, item);
                            }
                        });
                        $(ul).find("li:odd").addClass("odd");
                    };

                    $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                        return $("<li>")
                                .append("<div class='name font-bold text-sm p-xs b-b bg-light'>" + item.label + "</div>")
                                .append("<div class='pu_content bg-white p-sm' style='font-size: 11px;'><b>" + item.type + "</b>: " + item.number + "</div>")
                                //.append('<a>' + item.label + '<br>' + item.value + '</a>')
                                .appendTo(ul);
                    };

                    $(this).data('ui-autocomplete')._resizeMenu = function() {
                        this.menu.element.outerWidth(300);
                    };
                }
            });
        },
        
        loadInstantHistory: function() {

            if( $("#instant-history").is(":visible") ) {

                var self = this;
                var url = $("#instant_history_url").val();

                $("#instant-history").html("Loading ...");

                $.ajax({
                    url: url,
                    type: 'post',
                    success: function( response ) {
                        self.loaded = true;

                        $("#instant-history").html(response);
                    },
                    error: function( xhr ) {
                        console.log(xhr.responseText);
                    }
                });
            }
        }
    };
    
    App.register('SMSInstantMessaging', InstantMessagingModule);
})();
